// pages/firmOrder/firmOrder.js
const app = getApp();
const util = require("../../utils/util.js");
const api = require("../../utils/api.js");
Page({

    /**
     * 页面的初始数据
     */
    data: {
        //商品数据
        goodInfoArr: [],
        //商家信息
        shopInfo: {},
        //邮费内容
        postage: "",
        //满减公告
        fullCutContents: '',
        priceInfo: {
            //商品金额
            goodsPrice: 0,
            //满减金额
            cutPrice: 0,
            //红包金额
            redPacket: 0,
            //运费
            freight: 0,
            //使用多少红包
            useRedPacket:0
        },
        //支付金额
        totalPrice: 0,
        //红包剩余
        balance: 0,
        address: {
            name: "",
            mobile: "",
            nationalCode: "",
            address: "请选择地址",
            show: true,
        },
       
        pageColor: app.pageColor.mainColor,
        appid: app.globalData.appid,
        secret: app.globalData.secret,
        order_sn:""
    },
    /**
     * 进入产品详情页
     */
    toDetail: function (res){
        var goodId = res.currentTarget.dataset.goodid;
        this.navigateTo("../goodDetail/goodDetail?goodId=" + goodId)
    },

    /**
     * 立即支付
     */
    payBtn: function () {
        if (this.data.address.nationalCode == "") {
            this.choseAddress();
            return
        }
        //创建订单
        this.createOrder()
    },
    /**
     * 创建订单
     */
    createOrder:function(){
        var recom_id = util.getStorage("recom_id")
        let url = api.makeOrder();
        if (recom_id ==""){
            recom_id = 0
        }
        util.http(true, "POST", url, { goodInfoArr: this.data.goodInfoArr, priceInfo: this.data.priceInfo, totalPrice: this.data.totalPrice, recom_id: recom_id}, this.createOrderCallBack);
    },

    /**
     * 创建订单回调
     */
    createOrderCallBack: function (res) {
        var order_sn = res.order_sn;
        this.setData({
            order_sn: order_sn
        })
        //获取openID
        util.getOpenID(this.data.appid, this.data.secret,this.getOpenIDCallBack);
    },
    /**
     * 获取openID回调
     */
    
    getOpenIDCallBack: function (openid) {
        this.getPayInfo(openid);
    },
    /**
     * 获取支付信息
     */
    getPayInfo: function (openid){
        let url = api.orderPay();
        util.http(true, "POST", url, { app_id: this.data.appid, order_sn: this.data.order_sn, openid: openid }, this.getPayInfoCallBack)
    },

    /**
     * 支付信息回调
     */
    getPayInfoCallBack:function(res){
        //发起支付
        this.requestPay(res);

    },
    /**
     * 发起支付
     */
    requestPay: function (res){
        util.pay(res, this.requestPayCallBack)
    },
    /**
     * 吊起支付回调
     */
    requestPayCallBack:function(res){
        this.navigateTo("../order/order")
    },

    /**
     * 计算支付总金额
     */
    totalPrice: function () {
        var priceInfo = this.data.priceInfo;
        var newPrice = priceInfo.goodsPrice - priceInfo.cutPrice
        newPrice = newPrice >= 0 ? newPrice : 0
        if (priceInfo.redPacket >= newPrice) {
            priceInfo.useRedPacket = newPrice
            this.setData({
                balance: priceInfo.redPacket - newPrice,
                totalPrice: priceInfo.freight,
                priceInfo: this.data.priceInfo
            })
        } else {
            priceInfo.useRedPacket = priceInfo.redPacket
            this.setData({
                balance: 0,
                totalPrice: newPrice - priceInfo.redPacket + priceInfo.freight,
                priceInfo: this.data.priceInfo
            })
        }

    },
    /**
     * 选择地址
     */
    choseAddress: function () {
        util.chooseAddress(this.choseAddressCallBack);
    },
    /**
     * 选择地址回调
     */
    choseAddressCallBack: function (res) {
        console.log(res)
        this.data.address.address = res.provinceName + res.cityName + res.countyName + res.detailInfo;
        this.data.address.name = res.userName
        this.data.address.mobile = res.telNumber
        this.data.address.nationalCode = res.nationalCode.substring(0, 2);
        this.setData({
            address: this.data.address
        })
        //保存地址
        this.saveAddress()
        //计算邮费
        this.calculateFreight(this.data.address.nationalCode)
    },

    /**
     * 保存地址
     */
    saveAddress: function () {
        let url = api.addAddress();
        util.http(true, "POST", url, {  nationalCode: this.data.address.nationalCode, address: this.data.address.address, mobile: this.data.address.mobile, name: this.data.address.name }, this.saveAddressCallBack);
    },
    /**
     * 保存地址回调
     */
    saveAddressCallBack:function(res){
    },

    /**
     * 页面跳转
     */
    navigateTo: function (url) {
        wx.navigateTo({
            url: url
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var goodInfoArr = JSON.parse(options.goodInfoArr)
        //计算商品价格"
        this.data.priceInfo.goodsPrice = this.calculateGoodPrice(goodInfoArr);
        this.setData({
            goodInfoArr: goodInfoArr,
            priceInfo: this.data.priceInfo
        })
    },
    onReady: function () {
        util.setNavigationBarTitle("确认订单");
    },
    /**
     * 获取用户信息
     */
    getUserInfo: function () {
        let url = api.userInfo();
        util.http(true,"GET", url, "", this.getUserInfoCallBack);
    },

    /**
     * 获取用户信息回调
     */
    getUserInfoCallBack: function (res) {
        this.data.priceInfo.redPacket = res.red
        this.setData({
            priceInfo: this.data.priceInfo,
             address: res.address
        })
        //计算商品总金额
        this.totalPrice()
    },

    //计算商品总金额
    calculateGoodPrice: function (goodInfoArr) {
        var goodsPrice = 0;
        for (var i = 0; i < goodInfoArr.length; i++) {
            goodsPrice += goodInfoArr[i].goodPrice * goodInfoArr[i].goodCount
        }
        return goodsPrice;
    },
    //计算满减优惠金额
    calculateCutPrice: function (goodsPrice, full_cut) {
        //对满减从大到小排序
        var sortFullArr = full_cut.sort(function (a, b) {
            return b.price - a.price
        });
        //消费金额达到满减条件
        for (var i = 0; i < sortFullArr.length; i++) {
            //找到满足条件
            if (goodsPrice > sortFullArr[i].price) {
                this.data.priceInfo.cutPrice = sortFullArr[i].cut
                this.setData({
                    priceInfo: this.data.priceInfo
                })
                break;
            }
        }
    },

    //计算邮费
    calculateFreight: function (nationalCode) {
        var noFreeArr = this.data.shopInfo.no_free;
        for (var i = 0; i < noFreeArr.length; i++) {
            for (var j = 0; j < noFreeArr[i].detail.length; j++) {
                if (nationalCode == noFreeArr[i].detail[j].province_id) {
                    this.data.priceInfo.freight = noFreeArr[i].price
                    console.log("this.data.priceInfo.freight=" + this.data.priceInfo.freight)
                    this.setData({
                        priceInfo: this.data.priceInfo
                    })
                    break;
                }
            }
        }
    },

    /**
     * 获取商铺信息
     */

    getShopInfo(url) {
        util.http(true,"GET", url, '', this.getShopInfoCallBack)
    },
    /**
     * 获取商铺信息回调
     */

    getShopInfoCallBack(res) {
        var postage = ""
        var fullCutContents = res.full_cut.length == 0 ? "暂无满减活动" : "";

        //全场包邮
        if (res.Free_ship == 0 && res.no_free.length == 0) {
            postage = "本店所有商品全场包邮。"
        }
        //全场包邮含有不包邮区域
        else if (res.Free_ship == 0 && res.no_free.length != 0) {
            postage = "本店所有商品全场包邮,部分区域不包邮"
        }
        //满多少包邮
        else if (res.Free_ship != 0 && res.no_free.length != 0) {
            postage = "本店所有商品满" + res.Free_ship + "包邮,部分区域不包邮"
        } else {
            postage = "本店所有商品满" + res.Free_ship + "包邮"

        }

        for (var i = 0; i < res.full_cut.length; i++) {
            fullCutContents += "满" + res.full_cut[i].price + "减" + res.full_cut[i].cut + ";"
        }
        this.setData({
            postage: postage,
            shopInfo: res,
            fullCutContents: fullCutContents
        })
        //计算满减
        if (res.full_cut.length != 0) {
            this.calculateCutPrice(this.data.priceInfo.goodsPrice, res.full_cut)
        }
        this.getUserInfo()
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let url = api.shopInfo();
        this.getShopInfo(url)
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        clearInterval();
    },
})